<template>
  <view class="demo" @click="onAllClonse">
    <nut-skeleton v-if="show && !storeData.length" width="750rpx" height="15px" animated row="3" />

    <nut-swipe-group lock>
      <nut-swipe ref="swipeRef" v-for="item in storeData" :key="item.id" :name="item.id">
        <ShelfLife :data="item" />
        <template #right>
          <view class="del" @click="onDelate(item.id)">删除</view>
        </template>
      </nut-swipe>
    </nut-swipe-group>
  </view>

  <nut-tab-pane title="empty" pane-key="0" v-if="!show && !storeData.length">
    <nut-empty image="empty" description="没有记录，点击按钮添加记录吧！" />
  </nut-tab-pane>

  <view
    class="add"
    :style="buttonStyle"
    @click="
      () => {
        useScan();
        onAllClonse();
      }
    "
  >
    <nut-icon name="scan2" />
  </view>
  <view
    class="add edit"
    :style="buttonStyle"
    @click="
      () => {
        onLink('/pages/edit/index');
        onAllClonse();
      }
    "
  >
    <nut-icon name="edit" />
  </view>
</template>

<script setup>
import ShelfLife from "@/components/shelf-life/index.vue";
import useScan from "@/hooks/useScan";
import { getStore, deleteStore } from "@/api/store";
import { ref } from "vue";
import { onLink } from "@/hooks/useRoute";
import useModal from "@/hooks/useModal";
import { onShow } from "@dcloudio/uni-app";

const storeData = ref([]);
const show = ref(false);
const swipeRef = ref(null);
const buttonInterval = ref(null);
const buttonStyle = ref({});

onShow(() => {
  getStoreData();
  startButtonInterval();
});

function getStoreData() {
  show.value = true;
  getStore().then(({ data }) => {
    storeData.value = data;
    show.value = false;
  });
}

function startButtonInterval() {
  clearTimeout(buttonInterval.value);
  buttonStyle.value = {
    opacity: 1,
  };
  buttonInterval.value = setTimeout(() => {
    buttonStyle.value = {
      opacity: 0.3,
    };
  }, 5000);
}

function onAllClonse() {
  swipeRef.value.map((item) => item?.close());
}

function onEdit(id) {
  onAllClonse();
  onLink(`/pages/edit/index?id=${id}`);
}

function onDelate(id) {
  useModal({
    title: "确认删除？",
    success: ({ confirm }) => {
      if (confirm) {
        deleteStore({ id }).then(() => {
          getStoreData();
        });
      }
    },

    complete() {
      onAllClonse();
    },
  });
}
</script>

<style>
.demo {
  height: 100%;
  width: 750rpx;
  overflow: hidden;
}

.add {
  position: fixed;
  bottom: 140rpx;
  right: 20rpx;
  height: 90rpx;
  width: 90rpx;
  background: #fec000;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 700;
  transition: all 0.5s;
}

.edit {
  bottom: 250rpx;
}

.del {
  padding: 0 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #fff;
  font-weight: 700;
  background: red;
  /* border-radius: 10rpx 0 0 10rpx; */
}
</style>
